package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.CookieData;
import bsi.vn.FirstApp.ATMDetailActivity.MyListener;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ValidFragment")
public class ATMGeneralFragment extends SupportMapFragment {
	private Context _context;
	private int _iATMId;
	private ListView lvTicket;
	private String glo_sResult;
	private Location currentLocation;
	private SupportMapFragment fragment;
	private GoogleMap gMap;
	private double currentLat;
	private double currentLng;
	private TextView tvSerialNo;
	private TextView tvType;
	private TextView tvAddress;
	private TextView tvArea;
	private TextView tvCustomer;
	private TextView tvModel;
	private TextView tvKey;
	private TextView tvDeploy;
	private TextView tvHanded;
	private View rootView;

	
	public ATMGeneralFragment() {
	}

	public ATMGeneralFragment(Context context, int atmid) {
		_context = context;
		_iATMId = atmid;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		if (rootView != null) {
			ViewGroup parent = (ViewGroup) rootView.getParent();
			if (parent != null)
				parent.removeView(rootView);
		}
		try {
			rootView = inflater.inflate(R.layout.fragment_atmgeneral,
					container, false);
		} catch (InflateException e) {
			Log.d("test", "Inflate Exception");
		}

//		 rootView = inflater.inflate(R.layout.fragment_atmgeneral, container,
//		 false);
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		
		
		tvSerialNo = (TextView) rootView.findViewById(R.id.adtvSerialNo);
		tvType = (TextView) rootView.findViewById(R.id.adtvType);
		tvAddress = (TextView) rootView.findViewById(R.id.adtvAddress);
		tvArea = (TextView) rootView.findViewById(R.id.adtvArea);
		tvCustomer = (TextView) rootView.findViewById(R.id.adtvCustomer);
		tvModel = (TextView) rootView.findViewById(R.id.adtvModel);
		tvKey = (TextView) rootView.findViewById(R.id.adtvKey);
		tvDeploy = (TextView) rootView.findViewById(R.id.adtvDeploy);
		tvHanded = (TextView) rootView.findViewById(R.id.adtvHanded);

		fragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
		gMap  = fragment.getMap();

		/*
		 * LocationManager locationManager = (LocationManager)
		 * _context.getSystemService(_context.LOCATION_SERVICE);
		 * 
		 * boolean isGPSEnabled = locationManager
		 * .isProviderEnabled(LocationManager.GPS_PROVIDER); boolean
		 * isNetworkEnabled = locationManager
		 * .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if
		 * (isGPSEnabled == false && isNetworkEnabled == false) { // no network
		 * is enabled; } else { String locationProvider =
		 * LocationManager.GPS_PROVIDER; LocationListener mlistener = new
		 * MyListener();
		 * locationManager.requestLocationUpdates(locationProvider, 0, 0,
		 * mlistener); }
		 */
		myASTATMDetail myWebFetch = new myASTATMDetail();
		myWebFetch.execute(String.valueOf(_iATMId));
//		loadMaker(9.574715, 105.978407, R.drawable.atm32);
		return rootView;

	}

	private class myASTATMDetail extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				glo_sResult = GetATMDetail(Integer.parseInt(params[0]));

			} catch (Exception e) {
				e.printStackTrace();
			}
			return glo_sResult;
		}

		@Override
		protected void onPostExecute(String result) {
			String sResponse[] = result.split("\\|");

			if (Integer.parseInt(sResponse[0]) != 0) {
				Toast.makeText(_context, sResponse[1], Toast.LENGTH_SHORT)
						.show();
				return;
			}
			try {
				JSONArray jArray = new JSONArray(sResponse[1]);
				JSONObject json_data = jArray.getJSONObject(0);

				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"dd/MM/yyyy HH:mm");
				dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

				tvSerialNo.setText(json_data.getString(Consts.SDB_SERIALNO));
				tvType.setText(json_data.getString(Consts.SDB_TYPE));
				tvModel.setText(json_data.getString(Consts.SDB_MODELATM));

				tvCustomer.setText(json_data.getString(Consts.SDB_CUSTOMER));
				tvAddress.setText(json_data.getString(Consts.SDB_ADDRESS)
						+ ", " + json_data.getString(Consts.SDB_PROVINCE));
				tvArea.setText(json_data.getString(Consts.SDB_AREA));

				String temp = json_data.getString(Consts.SDB_HANDED).trim();

				if (temp.length() != 0)
					tvHanded.setText(dateFormat.format(ProcessFunc
							.stringToDate(temp, "ddMMyyyyHHmm")));

				temp = json_data.getString(Consts.SDB_DEPLOY).trim();
				if (temp.length() != 0)
					tvDeploy.setText(dateFormat.format(ProcessFunc
							.stringToDate(temp, "ddMMyyyyHHmm")));
				tvKey.setText(json_data.getString(Consts.SDB_KEY));
				double lat = json_data.getDouble(Consts.SDB_LAT);
				double lng = json_data.getDouble(Consts.SDB_LNG);
				// loadMaker(lat, lng, R.drawable.atm48);
				currentLat = lat;
				currentLng = lng;
				// Toast.makeText(ATMDetailActivity.this, ""+ lat,
				// Toast.LENGTH_LONG).show();
				// currentLocation();

			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString());
			}
		}

		@Override
		protected void onPreExecute() {
			// CheckDataValid();
			// showProgress(true);
			// super.onPreExecute();
			// tv.setText("Started Running….");
		}

		@Override
		protected void onProgressUpdate(String... text) {
			// finalResult.setText(text[0]);
			// Things to be done while execution of long running operation is in
			// progress. For example updating ProgessDialog
		}
	}

	private String GetATMDetail(int atmid) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc.GetCookie(_context);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_ATMDETAIL));
			nameValuePair.add(new BasicNameValuePair(Consts.V_ATMID, String
					.valueOf(atmid)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("test", "Error converting result " + e.toString());
		}
		return result;
	}

	public void loadMaker(double lat, double lng, int icon) {
		// SupportMapFragment fragment = (SupportMapFragment)
		// getChildFragmentManager().findFragmentById(R.id.map);
		// GoogleMap gMap = fragment.getMap();
		MarkerOptions markerOptions = new MarkerOptions();
		markerOptions.title("my marker");
		markerOptions.icon(BitmapDescriptorFactory.fromResource(icon));
		LatLng laLng = new LatLng(lat, lng);
		markerOptions.position(laLng);
		gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(laLng, 10));
		Marker marker = gMap.addMarker(markerOptions);
		marker.setDraggable(false);
	}

	public void MakePolyline(GoogleMap map, LatLng a, LatLng b) {
		PolylineOptions polylineOptions = new PolylineOptions();
		polylineOptions.add(a, b).width(5).color(Color.RED);
		Polyline line = map.addPolyline(polylineOptions);
	}

	public class MyListener implements LocationListener {

		@Override
		public void onLocationChanged(Location loc) {
			loadMaker(loc.getLatitude(), loc.getLongitude(), R.drawable.you32);
			LatLng a = new LatLng(loc.getLatitude(), loc.getLongitude());
			LatLng b = new LatLng(currentLat, currentLng);

			// currentLocation = loc;
			MakePolyline(gMap, a, b);
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

	}

	public void direction() {

	}

	public static String getUrl(double fromLat, double fromLon, double toLat,
			double toLon) {// connect to map web service
		StringBuffer urlString = new StringBuffer();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");// from
		urlString.append(Double.toString(fromLat));
		urlString.append(",");
		urlString.append(Double.toString(fromLon));
		urlString.append("&daddr=");// to
		urlString.append(Double.toString(toLat));
		urlString.append(",");
		urlString.append(Double.toString(toLon));
		urlString.append("&ie=UTF8&0&om=0&output=kml");
		return urlString.toString();
	}

}
